package com.fanxuankai.boot.web.advice;

import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.fanxuankai.commons.domain.Result;
import com.fanxuankai.commons.util.ResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * EasyExcel 异常处理
 *
 * @author fanxuankai
 */
@Order(1000)
@RestControllerAdvice
@ConditionalOnClass({ExcelDataConvertException.class})
public class EasyExcelExceptionAdvice extends NormalExceptionAdvice {
    private static final Logger LOGGER = LoggerFactory.getLogger(EasyExcelExceptionAdvice.class);

    /**
     * ExcelDataConvertException
     *
     * @param e 异常
     * @return 响应体
     */
    @ExceptionHandler({ExcelDataConvertException.class})
    public Result<Void> excelDataConvertException(ExcelDataConvertException e) {
        LOGGER.error("Excel 数据转换异常", e);
        return ResultUtils.fail(String.format("%s行%s列数据转换异常，请检查表格数据：%s",
                e.getRowIndex() + 1, e.getColumnIndex() + 1,
                e.getCellData().getStringValue()));
    }

    /**
     * ExcelAnalysisException
     *
     * @param e 异常
     * @return 响应体
     */
    @ExceptionHandler({ExcelAnalysisException.class})
    public Result<Void> excelAnalysisException(ExcelAnalysisException e) {
        if (e.getCause() instanceof ExcelDataConvertException) {
            return excelDataConvertException((ExcelDataConvertException) e.getCause());
        }
        return exceptionHandler(e);
    }
}
